package com.aiti.lulian.gxmh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.constant.SupplyToCRMConstant;
import com.aiti.lulian.dto.crm.SupplyToCRMParamDto;
import com.aiti.lulian.entity.CustomerContacts;
import com.aiti.lulian.entity.CustomerManagement;
import com.aiti.lulian.entity.EnterpriseDictData;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.gxmh.dto.GxmhCRMParamDto;
import com.aiti.lulian.gxmh.dto.SysUserDto;
import com.aiti.lulian.gxmh.dto.XLBEnterpriseLinkParamDto;
import com.aiti.lulian.gxmh.dto.XLBSerachWrapper;
import com.aiti.lulian.gxmh.entity.*;
import com.aiti.lulian.gxmh.service.GxmhTkVisitEnterpriseService;
import com.aiti.lulian.gxmh.vo.GxmhUserVisitHistoryVo;
import com.aiti.lulian.gxmh.vo.GxmhYunyangDataVo;
import com.aiti.lulian.gxmh.vo.GxmhZhaoTouBiaoItemVo;
import com.aiti.lulian.gxmh.vo.GxmhZhaoTouBiaoVo;
import com.aiti.lulian.mapper.CustomerManagementMapper;
import com.aiti.lulian.mapper.SysAreaMapper;
import com.aiti.lulian.mapper.gxmh.*;
import com.aiti.lulian.service.ICustomerContactsService;
import com.aiti.lulian.service.IEnterpriseDictDataService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * description: 小蓝本请求服务实现类
 * auth fcb
 * date 2025-06-13 16:09
 **/
@Service
@Slf4j
public class GxmhXLBService {

    // 拓客版
    private static final List<Integer> MINI_PROGRAM_VERSION_LIST = Arrays.asList(5);

    // 我们公司的企业id
    private static final String DE_JI_ENTERPRISE_ID = "000b4b09-8dc7-4680-95df-5085fc32dbd0";

    private static final Integer DEFAULT_COUNT = 50;

    @Autowired
    private GxmhXLBHttpRequestService gxmhXLBHttpRequestService;
    @Autowired
    private GxmhEnterpriseMapper gxmhEnterpriseMapper;
    @Autowired
    private GxmhEnterpriseLinkCountMapper gxmhEnterpriseLinkCountMapper;
    @Autowired
    private CustomerManagementMapper customerManagementMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private GxmhTkCurrentSearchMapper gxmhTkCurrentSearchMapper;
    @Autowired
    private GxmhTkVisitHistoryMapper gxmhTkVisitHistoryMapper;
    @Autowired
    private GxmhSysMapper gxmhSysMapper;
    @Autowired
    private ICustomerContactsService customerContactsService;
    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;
    @Autowired
    private IEnterpriseDictDataService enterpriseDictDataService;
    @Autowired
    private GxmhTkVisitEnterpriseMapper gxmhTkVisitEnterpriseMapper;

    /**
     * 标准版高级搜索接口元数据
     * @return
     */
    public Message requestSearchMeta(String userId) {
        this.checkCanUseXLBSearch(userId);
        return gxmhXLBHttpRequestService.requestGet("4035", null);
    }

    /**
     * 标准版高级搜索接口
     * @param wrapper
     * @return
     */
    public Message requestSearch(XLBSerachWrapper wrapper) {
        this.checkCanUseXLBSearch(wrapper.getUserId());
        try {
            String userId = wrapper.getUserId();
            if(StrUtil.isNotBlank(wrapper.getKeyword()) && StrUtil.isNotEmpty(userId) && !"null".equals(userId) && !"undefined".equals(userId)) {
                Integer currentCount = gxmhTkCurrentSearchMapper.queryUserKeywordCount(wrapper.getUserId(), wrapper.getKeyword());
                if (currentCount == 0) {
                    GxmhTkCurrentSearch currentSearch = new GxmhTkCurrentSearch();
                    currentSearch.setBaseId(IdUtil.simpleUUID());
                    currentSearch.setUserId(wrapper.getUserId());
                    currentSearch.setKeyword(wrapper.getKeyword());
                    currentSearch.setBaseCreateTime(new Date());
                    currentSearch.setSearchCount(1);
                    currentSearch.setBaseUpdateTime(new Date());
                    gxmhTkCurrentSearchMapper.insert(currentSearch);
                } else {
                    gxmhTkCurrentSearchMapper.updateSearchCount(wrapper.getUserId(), wrapper.getKeyword());
                }
            }
        }catch (Exception e) {
            log.error("记录用户搜索信息异常：{}", ExceptionUtil.stacktraceToString(e));
        }

        return gxmhXLBHttpRequestService.requestPost("4060", JSONUtil.toJsonStr(wrapper));
    }

    /**
     * 根据eid查询企业信息
     * @param eid
     * @return
     */
    public Message requestEnterpriseInfoByEid(String eid, String userId) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        Message message = gxmhXLBHttpRequestService.requestGet("1001", map);
        if(StrUtil.isNotEmpty(userId) && !"null".equals(userId) && !"undefined".equals(userId)) {
            this.recordVisitHistory(eid, userId, message);
        }
        return message;
    }

    /**
     * 根据信用代码查询公司
     * @param uscc
     * @return
     */
    public Message requestEnterpriseInfoByUscc(String uscc) {
        Map<String, String> map = new HashMap<>();
        map.put("uscc", uscc);
        Message message = gxmhXLBHttpRequestService.requestGet("4070", map);
        return message;
    }

    private void recordVisitHistory(String eid, String userId, Message message) {
        try {
            if(MessageCodeConstant.MSG_SUCCESS_CODE.equals(message.getCode())) {
                String entname = null;
                String unicode = null;
                JSONObject jsonObject = (JSONObject) message.getObj();
                if(jsonObject.containsKey("entInfo")) {
                    JSONObject entInfo = jsonObject.getJSONObject("entInfo");
                    if(entInfo.containsKey("base")) {
                        JSONObject base = entInfo.getJSONObject("base");
                        if(base.containsKey("entname")) {
                            entname = base.getString("entname");
                        }
                        if(base.containsKey("creditCode")) {
                            unicode = base.getString("creditCode");
                        }
                    }
                }
                if(StrUtil.isNotBlank(entname) && StrUtil.isNotBlank(unicode)) {
                    Integer count = gxmhTkVisitHistoryMapper.queryUserVisitHistoryCount(userId, entname);
                    if(count == 0) {
                        GxmhTkVisitHistory visitHistory = new GxmhTkVisitHistory();
                        visitHistory.setBaseId(IdUtil.simpleUUID());
                        visitHistory.setUserId(userId);
                        visitHistory.setEid(eid);
                        visitHistory.setEnterpriseName(entname);
                        visitHistory.setUnicode(unicode);
                        visitHistory.setBaseCreateTime(new Date());
                        visitHistory.setBaseUpdateTime(new Date());
                        gxmhTkVisitHistoryMapper.insert(visitHistory);
                    }else {
                        gxmhTkVisitHistoryMapper.updateVisitHistory(userId, entname);
                    }
                }
            }
        }catch (Exception e) {
            log.error("记录用户访问信息异常：{}", ExceptionUtil.stacktraceToString(e));
        }
    }

    /**
     * 根据eid查询企业股东信息
     * @param eid
     * @return
     */
    public Message requestEnterpriseShareholderInfoByEid(String eid, Integer pageIndex, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        return gxmhXLBHttpRequestService.requestGet("1041", map);
    }

    /**
     * 根据eid查询企对外投资
     * @param eid
     * @return
     */
    public Message requestEnterpriseInvestmentInfoByEid(String eid, Integer pageIndex, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        return gxmhXLBHttpRequestService.requestGet("1061", map);
    }

    /**
     * 获取企业网店信息
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @param type
     * @return
     */
    public Message requestEnterpriseNetShopByEid(String eid, Integer pageIndex, Integer pageSize, String type) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        if(StrUtil.isNotBlank(type)) {
            map.put("type", type);
        }
        return gxmhXLBHttpRequestService.requestGet("3521", map);
    }

    /**
     * 查询企业App信息
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Message requestEnterpriseAppByEid(String eid, Integer pageIndex, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        return gxmhXLBHttpRequestService.requestGet("3531", map);
    }

    /**
     * 获取企业新媒体信息
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Message requestEnterpriseNewMediaByEid(String eid, Integer pageIndex, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        return gxmhXLBHttpRequestService.requestGet("3501", map);
    }

    /**
     * 通过公司ID查询企业变更记录，返回工商变更事项、变更前后信息等字段的详细信息
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @param beginAltdate 空为全部；如果指定日期 yyyy-MM-dd 则表示当前日期之后
     * @param altItemType 变更类型；空为全部
     * @return
     */
    public Message requestEnterpriseAlterRecordByEid(String eid, Integer pageIndex, Integer pageSize, String beginAltdate, String altItemType) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        if(StrUtil.isNotBlank(beginAltdate)) {
            map.put("beginAltdate", beginAltdate);
        }
        if(StrUtil.isNotBlank(altItemType)) {
            map.put("altItemType", altItemType);
        }
        return gxmhXLBHttpRequestService.requestGet("1031", map);
    }

    /**
     * 查询企业知识产权统计
     * @param eid
     * @return
     */
    public Message requestEnterpriseAggZhiChanInfoByEid(String eid) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        return gxmhXLBHttpRequestService.requestGet("3070", map);
    }

    /**
     * 查询企业专利信息
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Message requestEnterprisePagerParentInfo(String eid, Integer pageIndex, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        return gxmhXLBHttpRequestService.requestGet("3021", map);
    }

    /**
     * 获取企业分页商标信息
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Message requestEnterprisePagerTrademarksByEid(String eid, Integer pageIndex, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        return gxmhXLBHttpRequestService.requestGet("3001", map);
    }

    /**
     * 获取软件著作权
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @param year
     * @return
     */
    public Message requestEnterprisePagerSoftwareCopyrightByEid(String eid, Integer pageIndex, Integer pageSize, String year) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        if(StrUtil.isNotBlank(year)) {
            map.put("year", year);
        }
        return gxmhXLBHttpRequestService.requestGet("3041", map);
    }

    /**
     * 查询企业作品著作权
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @param year
     * @return
     */
    public Message requestEnterprisePagerWorkCopyrightByEid(String eid, Integer pageIndex, Integer pageSize, String year) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        if(StrUtil.isNotBlank(year)) {
            map.put("year", year);
        }
        return gxmhXLBHttpRequestService.requestGet("3061", map);
    }

    /**
     * 获取企业网站信息
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Message requestEnterprisePagerWebSitesByEid(String eid, Integer pageIndex, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        return gxmhXLBHttpRequestService.requestGet("3031", map);
    }

    /**
     * 查询企业风险数据
     * @param eid
     * @return
     */
    public Message requestEnterpriseZhaopinAndRiskByEid(String eid) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        return gxmhXLBHttpRequestService.requestGet("2680", map);
    }

    /**
     * 查询企业的行政处罚信息
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Message requestEnterprisePagerCasePubByEid(String eid, Integer pageIndex, Integer pageSize, String illegActType) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", pageIndex.toString());
        map.put("pageSize", pageSize.toString());
        if(StrUtil.isNotBlank(illegActType)) {
            map.put("illegActType", illegActType);
        }
        return gxmhXLBHttpRequestService.requestGet("2581", map);
    }

    /**
     * 法院公告列表
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @param annType
     * @return
     */
    public Message requestEnterprisePagerCourtAnnouncementsByEid(String eid, Integer pageIndex, Integer pageSize, String annType) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", pageIndex.toString());
        map.put("pageSize", pageSize.toString());
        if(StrUtil.isNotBlank(annType)) {
            map.put("annType", annType);
        }
        return gxmhXLBHttpRequestService.requestGet("2661", map);
    }

    /**
     * 查询企业的裁判文书信息
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @param type
     * @return
     */
    public Message requestEnterprisePagerCourtPjwsByEid(String eid, Integer pageIndex, Integer pageSize, String type) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", pageIndex.toString());
        map.put("pageSize", pageSize.toString());
        if(StrUtil.isNotBlank(type)) {
            map.put("type", type);
        }
        return gxmhXLBHttpRequestService.requestGet("4709", map);
    }

    /**
     * 查询企业的开庭公告
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Message requestEnterprisePagerCourtSessionAnnouncementsByEid(String eid, Integer pageIndex, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        return gxmhXLBHttpRequestService.requestGet("2601", map);
    }

    /**
     * 查询企业的招投标类型和数量。
     * 获取所有的招投标数据，过滤掉可能没有类型的，最后统计每一类公告的数量
     * @param eid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public List<GxmhYunyangDataVo> requestEnterpriseYunyangDataByEid(String eid) {
        int pageIndex = 1;
        int pageSize = 20;
        // 1. 请求招投标数据总数
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", "1");
        map.put("pageSize", "1");
        Integer totalCount = gxmhXLBHttpRequestService.requestTotalCount("1530",map, "get", "yunyangData", "zTB");
        // 2. 计算页数
        int pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        if(totalCount == 0) {
            return new ArrayList<>();
        }
        JSONArray jsonArray = new JSONArray();
        // 3. 循环获取所有招投标数据
        while (pageIndex <= pageCount) {
            map.put("pageIndex", String.valueOf(pageIndex));
            map.put("pageSize", String.valueOf(pageSize));
            Message message = gxmhXLBHttpRequestService.requestGet("1530", map);
            if(!message.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                throw new BusinessException("请求招投标数据失败");
            }
            JSONObject data = (JSONObject)message.getObj();
            JSONObject yunyangData = data.getJSONObject("yunyangData");
            if(yunyangData == null) {
                return new ArrayList<>();
            }
            JSONObject zTB = yunyangData.getJSONObject("zTB");
            if(zTB == null) {
                return new ArrayList<>();
            }
            JSONArray dataArray = zTB.getJSONArray("data");
            if(dataArray != null && !dataArray.isEmpty()) {
                jsonArray.addAll(dataArray);
            }
            pageIndex++;
        }
        if(jsonArray.isEmpty()) {
            return new ArrayList<>();
        }
        // 3. 过滤掉类型可能为空的数据，按类型分类并求和
        List<GxmhYunyangDataVo> collect = jsonArray.stream()
                .filter((item) -> {
                    JSONObject jsonObject = (JSONObject) item;
                    String typeStr = jsonObject.getString("typeStr");
                    return StrUtil.isNotBlank(typeStr) && !"null".equals(typeStr);
                }).map((item) -> {
                    JSONObject jsonObject = (JSONObject) item;
                    GxmhYunyangDataVo vo = new GxmhYunyangDataVo();
                    vo.setTypeStr(jsonObject.getString("typeStr"));
                    vo.setCount(1);
                    return vo;
                }).collect(Collectors.groupingBy(GxmhYunyangDataVo::getTypeStr, Collectors.summingInt(GxmhYunyangDataVo::getCount)))
                .entrySet().stream()
                .map(entry -> new GxmhYunyangDataVo(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * 查询企业招投标信息
     * @param eid
     * @return
     */
    public GxmhZhaoTouBiaoVo requestEnterpriseZhaoTouBiaoByEid(String eid) {
        int pageIndex = 1;
        int pageSize = 20;
        // 1. 请求招投标数据总数
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", "1");
        map.put("pageSize", "1");
        Integer totalCount = gxmhXLBHttpRequestService.requestTotalCount("1530",map, "get", "yunyangData", "zTB");
        // 2. 计算页数
        int pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        if(totalCount == 0) {
            GxmhZhaoTouBiaoVo zhaoTouBiaoVo = new GxmhZhaoTouBiaoVo();
            zhaoTouBiaoVo.setTypeList(new ArrayList<>());
            zhaoTouBiaoVo.setDataList(new ArrayList<>());
            return zhaoTouBiaoVo;
        }
        List<JSONObject> list = new ArrayList<>(totalCount);
        while (pageIndex <= pageCount) {
            map.put("pageIndex", String.valueOf(pageIndex));
            map.put("pageSize", String.valueOf(pageSize));
            Message message = gxmhXLBHttpRequestService.requestGet("1530", map);
            if (!message.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                throw new BusinessException("请求招投标数据失败");
            }
            JSONObject data = (JSONObject)message.getObj();
            JSONObject yunyangData = data.getJSONObject("yunyangData");
            if(yunyangData == null) {
                log.error("无法解析小蓝本接口数据：yunyangData");
                throw new BusinessException("请求招投标数据失败");
            }
            JSONObject zTB = yunyangData.getJSONObject("zTB");
            if(zTB == null) {
                log.error("无法解析小蓝本接口数据：zTB");
                throw new BusinessException("请求招投标数据失败");
            }
            JSONArray dataArray = zTB.getJSONArray("data");
            if(dataArray != null && !dataArray.isEmpty()) {
                for(int i = 0; i < dataArray.size(); i++) {
                    JSONObject obj = dataArray.getJSONObject(i);
                    list.add(obj);
                }
            }
            pageIndex++;
        }
        // 获取分类
        List<String> typeList = list.stream()
                .filter((item) -> {
                    String typeStr = item.getString("typeStr");
                    return StrUtil.isNotBlank(typeStr) && !"null".equals(typeStr);
                }).map((item) -> {
                    return item.getString("typeStr");
                }).distinct().collect(Collectors.toList());
        // 构建返回数据
        if(CollectionUtil.isEmpty(typeList)) {
            GxmhZhaoTouBiaoVo zhaoTouBiaoVo = new GxmhZhaoTouBiaoVo();
            zhaoTouBiaoVo.setTypeList(Arrays.asList(""));
            GxmhZhaoTouBiaoItemVo itemVo = new GxmhZhaoTouBiaoItemVo();
            itemVo.setTypeStr("");
            itemVo.setDataList(list);
            zhaoTouBiaoVo.setDataList(Arrays.asList(itemVo));
            return zhaoTouBiaoVo;
        }
        // 构建返回数据
        GxmhZhaoTouBiaoVo zhaoTouBiaoVo = new GxmhZhaoTouBiaoVo();
        zhaoTouBiaoVo.setTypeList(typeList);
        List<GxmhZhaoTouBiaoItemVo> itemList = new ArrayList<>(30);
        zhaoTouBiaoVo.setDataList(itemList);
        for(String type : typeList) {
            GxmhZhaoTouBiaoItemVo itemVo = new GxmhZhaoTouBiaoItemVo();
            itemVo.setTypeStr(type);
            List<JSONObject> jsonArray = new ArrayList<>();
            for(JSONObject item : list) {
                String typeStr = item.getString("typeStr");
                if(type.equals(typeStr)) {
                    jsonArray.add(item);
                }
            }
            itemVo.setDataList(jsonArray);
            itemList.add(itemVo);
        }
        return zhaoTouBiaoVo;
    }

    /**
     * 获取企业邮箱列表
     * @param eid
     * @return
     */
    public Message requestEnterpriseEmail(String eid) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        return gxmhXLBHttpRequestService.requestGet("2080", map);
    }

    /**
     * 根据eid查询企集团成员
     * @param eid
     * @return
     */
    public Message requestEnterpriseGroupMemberInfoByEid(String eid, Integer pageIndex, Integer pageSize) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", eid);
        map.put("pageIndex", String.valueOf(pageIndex));
        map.put("pageSize", String.valueOf(pageSize));
        return gxmhXLBHttpRequestService.requestGet("1051", map);
    }

    /**
     * 查询企业德联系方式
     * 该接口目前只在有KP条件的时候使用，只有分页条件，前端不使用该接口
     * @param eid
     * @return
     */
    public Message requestEnterpriseLinkInfoByEid(XLBEnterpriseLinkParamDto  dto) {
        Map<String, String> map = new HashMap<>();
        map.put("eid", dto.getEid());
        map.put("pageIndex", String.valueOf(dto.getPageIndex()));
        map.put("pageSize", String.valueOf(dto.getPageSize()));
        if(StrUtil.isNotEmpty(dto.getType())) {
            map.put("type", dto.getType());
        }
        if(dto.getOnlyKp() != null) {
            map.put("onlyKp", String.valueOf(dto.getOnlyKp()));
        }
        if(dto.getPhoneTag() != null) {
            map.put("phoneTag", String.valueOf(dto.getPhoneTag()));
        }
        return gxmhXLBHttpRequestService.requestGet("2041", map);
    }

    /**
     * 查询企业的联系方式，要求将KP电话放在前面
     * @param dto
     * @return
     */
    public Message requestEnterpriseLinkInfoByEidTopKP(XLBEnterpriseLinkParamDto  dto) {
        int pageSize = dto.getPageSize();
        // 所有企业的联系电话，最多取100个
        List<GxmhCustomerContactsDto> allEnterprisePhone = this.requestAllEnterprisePhone(dto.getEid(), dto.getType());
        if(CollectionUtil.isEmpty(allEnterprisePhone)) {
            return Message.success(this.buildJsonObject(allEnterprisePhone, dto.getPageIndex(), pageSize, 0));
        }
        // 计算最多返多少页
        int pageCount = (int)Math.ceil((double) allEnterprisePhone.size() / pageSize);
        int pageIndex = dto.getPageIndex();
        if(pageIndex < 1 || pageIndex > pageCount) {
            return Message.success(this.buildJsonObject(new ArrayList<>(), pageIndex, pageSize, allEnterprisePhone.size()));
        }
        // 将isKP是true的放在前面
        List<GxmhCustomerContactsDto> kpList = allEnterprisePhone.stream().sorted(Comparator.comparing(GxmhCustomerContactsDto::getIsKp).reversed()).collect(Collectors.toList());
        // 分页返回
        int startIndex = (pageIndex - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, allEnterprisePhone.size());
        List<GxmhCustomerContactsDto> result = kpList.subList(startIndex, endIndex);

        return Message.success(this.buildJsonObject(result, pageIndex, pageSize, allEnterprisePhone.size()));
    }

    private JSONObject buildJsonObject(List<GxmhCustomerContactsDto> list, Integer pageIndex, Integer pageSize, Integer totalCount) {
        JSONObject pagerContact = new JSONObject();
        pagerContact.put("totalCount", totalCount);
        pagerContact.put("pageIndex", pageIndex);
        pagerContact.put("pageSize", pageSize);
        pagerContact.put("data", list);
        JSONObject entInfo = new JSONObject();
        entInfo.put("pagerContact", pagerContact);
        JSONObject obj = new JSONObject();
        obj.put("entInfo", entInfo);
        return obj;
    }

    // 查询所有公司的电话，最多100个
    private List<GxmhCustomerContactsDto> requestAllEnterprisePhone(String eid, String type) {
        XLBEnterpriseLinkParamDto dto = new XLBEnterpriseLinkParamDto();
        dto.setEid(eid);
        dto.setType(type);
        dto.setPageSize(20);
        int pageIndex = 1;
        List<GxmhCustomerContactsDto> list = new ArrayList<>();
        while(true) {
            if(pageIndex > 5) {
                break;
            }
            dto.setPageIndex(pageIndex);
            Message message = this.requestEnterpriseLinkInfoByEid(dto);
            pageIndex++;
            if(!MessageCodeConstant.MSG_SUCCESS_CODE.equals(message.getCode())) {
                throw new BusinessException("获取企业联系人失败");
            }
            JSONObject jsonObject = (JSONObject)message.getObj();
            JSONObject entInfo = jsonObject.getJSONObject("entInfo");
            if(entInfo == null) {
                throw new BusinessException("获取企业联系人失败");
            }
            JSONObject pagerContact = entInfo.getJSONObject("pagerContact");
            if(pagerContact == null) {
                throw new BusinessException("获取企业联系人失败");
            }
            JSONArray data = pagerContact.getJSONArray("data");
            if(data == null || data.isEmpty()) {
                break;
            }
            for(int i = 0; i < data.size(); i++) {
               JSONObject item = (JSONObject)data.get(i);
               GxmhCustomerContactsDto contactsDto = new GxmhCustomerContactsDto();
                contactsDto.setLogo(item.getString("logo"));
                contactsDto.setName(item.getString("name"));
                contactsDto.setPhone(item.getString("phone"));
                contactsDto.setIsKp(item.getBoolean("isKp"));
                contactsDto.setSource(item.getString("source"));
                contactsDto.setAddDate(item.getString("addDate"));
               list.add(contactsDto);
            }
        }
        return list;
    }


    /**
     * 判读该用户是否拥有访问企业联系人的权限
     * @param userid
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public synchronized void accessEnterpriseLink(String userid, String eid) {
        // 1. 查询当前用户绑定的企业
        String enterpriseId = gxmhEnterpriseMapper.queryEnterpriseIdByUserId(userid);
        if(StrUtil.isEmpty(enterpriseId)) {
            throw new BusinessException("您当前还未绑定企业，无法查看企业联系人");
        }
        // 2. 查询当前企业的小程序版本。只有拓客版可以访问
        Integer miniProgramVersion = gxmhEnterpriseMapper.queryMiniProgramVersion(enterpriseId);
        if(miniProgramVersion == null || !MINI_PROGRAM_VERSION_LIST.contains(miniProgramVersion)) {
            throw new BusinessException( "请升级到拓客版本以查看企业联系人");
        }
        // 判断当前用户绑定的企业是否已经解锁当前查看的公司的联系人，防止多个同一公司的用户同时解锁同一个拓客企业，造成多扣减查看次数
        GxmhTkVisitEnterprise gxmhTkVisitEnterprise = gxmhTkVisitEnterpriseMapper.queryVisitedEnterprise(enterpriseId, eid);
        if(gxmhTkVisitEnterprise != null) {
            return;
        }
        // 3. 查询当前企业查询的剩余次数。如果查不到次数，则设置一个默认的次数（这样不用处理历史数据）。
        // 2025-07-15 修改：查看次数在云展厅后台配置
        GxmhEnterpriseLinkCount gxmhEnterpriseLinkCount = gxmhEnterpriseLinkCountMapper.queryEnterpriseLinkCount(enterpriseId);
        if(gxmhEnterpriseLinkCount == null) {
//            gxmhEnterpriseLinkCount = new GxmhEnterpriseLinkCount();
//            gxmhEnterpriseLinkCount.setBaseId(IdUtil.simpleUUID());
//            gxmhEnterpriseLinkCount.setEnterpriseId(enterpriseId);
//            gxmhEnterpriseLinkCount.setLinkCount(DEFAULT_COUNT - 1);
//            gxmhEnterpriseLinkCount.setBaseCreateTime(new Date());
//            gxmhEnterpriseLinkCountMapper.insert(gxmhEnterpriseLinkCount);
//            //  保存当前公司已经解锁过的拓客企业
//            this.saveVisitEnterprise(enterpriseId, eid, userid);
//            return;
            throw new BusinessException( "请升级到拓客版本以查看企业联系人");
        }
        Integer linkCount = gxmhEnterpriseLinkCount.getLinkCount();
        if(linkCount <= 0) {
            throw new BusinessException("您的查看联系人次数已用完");
        }
        // 4. 查看次数 - 1
        gxmhEnterpriseLinkCountMapper.updateEnterpriseLinkCount(enterpriseId);
        // 5. 保存当前公司已经解锁过的拓客企业
        this.saveVisitEnterprise(enterpriseId, eid, userid);
    }

    /**
     * 查询当前企业解锁联系人的次数
     * @param enterpriseId
     * @return
     */
    public Integer getEnterpriseLinkCount(String enterpriseId) {
        GxmhEnterpriseLinkCount gxmhEnterpriseLinkCount = gxmhEnterpriseLinkCountMapper.queryEnterpriseLinkCount(enterpriseId);
        if(gxmhEnterpriseLinkCount == null) {
            throw new BusinessException("未查询到当前企业的解锁次数");
        }
        return gxmhEnterpriseLinkCount.getLinkCount();
    }

    /**
     * 获取当前企业小程序版本
     * @param enterpriseId
     * @return
     */
    public Integer getEnterpriseMiniProgramVersion(String enterpriseId) {
        Integer miniProgramVersion = gxmhEnterpriseMapper.queryMiniProgramVersion(enterpriseId);
        if(miniProgramVersion == null) {
            throw new BusinessException("未查询到当前企业的小程序版本");
        }
        return miniProgramVersion;
    }

    private void saveVisitEnterprise(String enterpriseId, String eid, String userId) {
        GxmhTkVisitEnterprise gxmhTkVisitEnterprise = new GxmhTkVisitEnterprise();
        gxmhTkVisitEnterprise.setBaseId(IdUtil.simpleUUID());
        gxmhTkVisitEnterprise.setEnterpriseId(enterpriseId);
        gxmhTkVisitEnterprise.setEid(eid);
        gxmhTkVisitEnterprise.setBaseCreateBy(userId);
        gxmhTkVisitEnterprise.setBaseCreateTime(new Date());
        gxmhTkVisitEnterpriseMapper.insert(gxmhTkVisitEnterprise);
    }

    /**
     * 判断当前企业是否已经解锁联系人
     * @param enterpriseId
     * @return true 已经解锁； false 未解锁
     */
    public Boolean enterpriseUnlockLink(String userId, String eid) {
        String enterpriseId = gxmhEnterpriseMapper.queryEnterpriseIdByUserId(userId);
        if(StrUtil.isEmpty(enterpriseId)) {
            return false;
        }
        GxmhTkVisitEnterprise gxmhTkVisitEnterprise = gxmhTkVisitEnterpriseMapper.queryVisitedEnterprise(enterpriseId, eid);
        // 不是空表示已经解锁
        return gxmhTkVisitEnterprise != null;
    }

    /**
     * 添加企企信息到CRM
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    public void addEnterpriseToCRM(GxmhCRMParamDto dto) {
        // 0. 查询当前用户绑定的企业id
        String userBindingEnterpriseId = gxmhEnterpriseMapper.queryEnterpriseIdByUserId(dto.getUserId());
        if(StrUtil.isEmpty(userBindingEnterpriseId)) {
            throw new BusinessException("您当前还未绑定企业");
        }
        // 1. 根据信用代码查询企业id
//        String enterpriseId = gxmhEnterpriseMapper.queryEnterpriseIdByCreditCode(dto.getCreditCode());
//        if(StrUtil.isEmpty(enterpriseId)) {
//            throw new BusinessException("当前企业未在企业库中");
//        }
        // 2. 判断该企业是否已经添加到了CRM中
        Integer count = customerManagementMapper.queryCustomerCountByEnterpriseId(userBindingEnterpriseId, dto.getEntname());
        if(count > 0) {
            throw new BusinessException("该企业已添加到CRM中");
        }
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(dto.getUserId());
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        // 获取企业的联系人
        List<GxmhCustomerContactsDto> mobileList = this.requestAllEnterprisePhone(dto.getEid(), "mobile");
        List<GxmhCustomerContactsDto> fixPhoneList = this.requestAllEnterprisePhone(dto.getEid(), "tel");
        // 3. 添加企企到CRM
        CustomerManagement customerManagement = new CustomerManagement();
        String customerId = IdUtil.simpleUUID();
        customerManagement.setBaseId(customerId);
        customerManagement.setEnterpriseName(dto.getEntname());
        if(CollectionUtil.isNotEmpty(mobileList)) {
            customerManagement.setPhone(mobileList.get(0).getPhone());
        }
        if(CollectionUtil.isNotEmpty(fixPhoneList)) {
            customerManagement.setFixPhone(fixPhoneList.get(0).getPhone());
        }
        customerManagement.setCustomerStatus(SupplyToCRMConstant.DEFAULT_CUSTOMER_STATUS);
        customerManagement.setCreator(dto.getUserId());
        customerManagement.setBaseCreateTime(new Date());
        customerManagement.setCompanyId(userBindingEnterpriseId);
        // 负责人是当前登录账号
        customerManagement.setSaleResponsiblePerson(dto.getUserId());
        customerManagement.setSaleResponsiblePersonName(sysUserDto.getRealname());
        customerManagement.setIndustry(dto.getIndustryphyName());
        // 跟进状态 初访。查询这个绑定企业德初访状态的id，没有的话暂时设置通用的一个默认值
        List<EnterpriseDictData> cardCustomerFollowStatus = enterpriseDictDataService.list(new LambdaQueryWrapper<EnterpriseDictData>()
                .eq(EnterpriseDictData::getDictTypeNo, "CARD_CUSTOMER_FOLLOW_STATUS")
                .eq(EnterpriseDictData::getEnterpriseId, userBindingEnterpriseId)
                .orderByAsc(EnterpriseDictData::getSort));
        if(CollectionUtil.isNotEmpty(cardCustomerFollowStatus)) {
            customerManagement.setFollowStatus(cardCustomerFollowStatus.get(0).getBaseId());
        }else {
            customerManagement.setFollowStatus(SupplyToCRMConstant.FOLLOW_STATUS_1);
        }
        // 来源拓客4
        customerManagement.setCustomerFrom(4);
        customerManagement.setTkLogo(dto.getTkLogo());

        customerManagement.setAddress(dto.getAddress());
        customerManagement.setFrName(dto.getFrName());
        customerManagement.setRegcap(dto.getRegcap());
        customerManagement.setEsdate(DateUtil.parse(dto.getEsdate()));
        customerManagement.setDeptId(this.getUserDept(dto.getUserId()));
        customerManagement.setCustomerFromBaseId(dto.getEid());
        List<String> provinceBaseIdList = sysAreaMapper.getProvinceBaseIdUseLike(dto.getRegorgProvince());
        if(CollectionUtil.isNotEmpty(provinceBaseIdList) && provinceBaseIdList.size() == 1) {
            String provinceBaseId = provinceBaseIdList.get(0);
            customerManagement.setProvince(provinceBaseId);
            String cityId = sysAreaMapper.getCityOrCountyBaseId(dto.getRegorgCity(), provinceBaseId);
            customerManagement.setCity(cityId);
            String countyId = sysAreaMapper.getCityOrCountyBaseId(dto.getRegorgCounty(), cityId);
            customerManagement.setCounty(countyId);
        }
        customerManagementMapper.insert(customerManagement);
        // 添加联系人
        int num = 1;
        List<CustomerContacts> customerContactsList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(mobileList)) {
            for(GxmhCustomerContactsDto contactsDto : mobileList) {
                CustomerContacts customerContacts = new CustomerContacts();
                customerContacts.setBaseId(IdUtil.simpleUUID());
                if(StrUtil.isBlank(contactsDto.getName())) {
                    customerContacts.setContactsName("联系人-" + num);
                    num++;
                }else {
                    customerContacts.setContactsName(contactsDto.getName());
                }
                customerContacts.setContactsPhone(contactsDto.getPhone());
                customerContacts.setCustomerId(customerId);
                customerContacts.setTelephone(contactsDto.getPhone());
                customerContacts.setEnterpriseId(userBindingEnterpriseId);
                customerContacts.setDirectorId(dto.getUserId());
                customerContacts.setDirectorName(sysUserDto.getRealname());
                customerContacts.setCreator(dto.getUserId());
                customerContacts.setBaseCreateTime(new Date());
                customerContacts.setLogo(contactsDto.getLogo());

                customerContactsList.add(customerContacts);
            }
        }
        if(CollectionUtil.isNotEmpty(fixPhoneList)) {
            for(GxmhCustomerContactsDto contactsDto : fixPhoneList) {
                CustomerContacts customerContacts = new CustomerContacts();
                customerContacts.setBaseId(IdUtil.simpleUUID());
                if(StrUtil.isBlank(contactsDto.getName())) {
                    customerContacts.setContactsName("联系人-" + num);
                    num++;
                }else {
                    customerContacts.setContactsName(contactsDto.getName());
                }
                customerContacts.setContactsPhone(contactsDto.getPhone());
                customerContacts.setCustomerId(customerId);
                customerContacts.setTelephone(contactsDto.getPhone());
                customerContacts.setEnterpriseId(userBindingEnterpriseId);
                customerContacts.setDirectorId(dto.getUserId());
                customerContacts.setDirectorName(sysUserDto.getRealname());
                customerContacts.setCreator(dto.getUserId());
                customerContacts.setBaseCreateTime(new Date());
                customerContacts.setLogo(contactsDto.getLogo());

                customerContactsList.add(customerContacts);
            }
        }
        if(!customerContactsList.isEmpty()) {
            customerContactsService.saveBatch(customerContactsList);
        }
    }

    private String getUserDept(String userId) {
        Message userInfoMessage = cloudShowManagerSubService.getUserInfo(userId);
        if (userInfoMessage == null) {
            throw new RuntimeException("获取用户信息失败");
        } else if (!userInfoMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
            throw new RuntimeException("查询用户信息失败");
        } else {
            Object obj = userInfoMessage.getObj();
            if (obj == null) {
                throw new RuntimeException("查询用户为空");
            }
            ObjectMapper mapper = new ObjectMapper();
            Map userInfoMap = mapper.convertValue(obj, Map.class);
            String deptId = (String) userInfoMap.get("deptId");
            return deptId;
        }
    }

    /**
     * 查询当前用户的搜索记录
     * 目前只返回最近的10条
     * @param userId
     * @return
     */
    public List<GxmhTkCurrentSearch> queryCurrentSearchList(String userId) {
        return gxmhTkCurrentSearchMapper.queryUserKeywordList(userId);
    }

    /**
     * 删除用户搜索记录
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserCurrentSearch(List<String> baseIdList) {
        if(CollectionUtil.isEmpty(baseIdList)) {
            return;
        }
        gxmhTkCurrentSearchMapper.deleteBySearchIdList(baseIdList);
    }

    /**
     * 查询热门搜索
     * @return
     */
    public List<String> hotSearchKeywordList() {
        return gxmhTkCurrentSearchMapper.hotSearchKeywordList();
    }

    /**
     * 查询用户浏览历史
     * @param userId
     * @return
     */
    public List<GxmhUserVisitHistoryVo> queryUserVisitHistoryList(String userId) {
        return gxmhTkVisitHistoryMapper.queryUserVisitHistoryList(userId);
    }

    /**
     * 删除用户浏览历史
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserCurrentVisitHistory(List<String> baseIdList) {
        if(CollectionUtil.isEmpty(baseIdList)) {
            return;
        }
        gxmhTkVisitHistoryMapper.deleteBySearchIdList(baseIdList);
    }

    // 只有拓客版本的用户可以使用
    private void checkCanUseXLBSearch(String userId) {
        if(StrUtil.isEmpty(userId)) {
            throw new BusinessException("用户标识为空");
        }
        String enterpriseId = gxmhSysMapper.queryEnterpriseIdByUserId(userId);
        if(StrUtil.isEmpty(enterpriseId)) {
            throw new BusinessException("未查询到用户绑定的企业");
        }
        Integer miniProgramVersion = gxmhEnterpriseMapper.queryMiniProgramVersion(enterpriseId);
        if(miniProgramVersion == null || !MINI_PROGRAM_VERSION_LIST.contains(miniProgramVersion)) {
            throw new BusinessException( "请升级到拓客版本以解锁企业搜索功能");
        }
    }

}
